package com.mineoj.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.constant.CommonConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.model.dto.file.FileMessageQueryRequest;
import com.mineoj.model.entity.FileMessage;
import com.mineoj.model.entity.FileMessage;
import com.mineoj.model.entity.User;
import com.mineoj.model.enums.FileUploadBizEnum;
import com.mineoj.model.vo.FileMessageVO;
import com.mineoj.model.vo.UserVO;
import com.mineoj.service.FileMessageService;
import com.mineoj.mapper.FileMessageMapper;
import com.mineoj.service.UserService;
import com.mineoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 明月
* @description 针对表【file_message】的数据库操作Service实现
* @createDate 2025-04-11 10:13:48
*/
@Service
public class FileMessageServiceImpl extends ServiceImpl<FileMessageMapper, FileMessage>
    implements FileMessageService{

    @Resource
    private FileMessageMapper fileMessageMapper;

    @Resource
    private UserService userService;

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    public void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
        if (FileUploadBizEnum.USER_CODE.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
        }
    }

    /**
     * 保存文件
     *
     * @param file 文件
     * @param loginUser 用户登录
     * @param fileUploadBizEnum 业务类型
     */
    @Override
    public void saveFile(FileMessage file, User loginUser, FileUploadBizEnum fileUploadBizEnum) {
        // 用户头像
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            userService.update()
                    .eq("id", loginUser.getId())
                    .set("userAvatar", file.getFile())
                    .update();
        }
        // 用户代码
        else if (FileUploadBizEnum.USER_CODE.equals(fileUploadBizEnum)) {
            file.setCreateTime(new java.sql.Date(System.currentTimeMillis()));
            fileMessageMapper.insert(file);
        }
    }

    /**
     * 获取查询条件
     * @param fileMessageQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<FileMessage> getQueryWrapper(FileMessageQueryRequest fileMessageQueryRequest) {
        QueryWrapper<FileMessage> queryWrapper = new QueryWrapper<>();
        if (fileMessageQueryRequest == null) {
            return queryWrapper;
        }

        Long id = fileMessageQueryRequest.getId();
        String name = fileMessageQueryRequest.getName();
        Long userId = fileMessageQueryRequest.getUserId();
        String type = fileMessageQueryRequest.getType();
        String sortField = fileMessageQueryRequest.getSortField();
        String sortOrder = fileMessageQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(type), "type", type);

        queryWrapper
                .eq(ObjectUtils.isNotEmpty(id), "id", id)
                .eq(ObjectUtils.isNotEmpty(userId), "userId", userId);

        // 排序逻辑
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 将题目对象转换为题目视图对象，并关联查询用户信息。
     * @param fileMessage
     * @param request
     * @return
     */
    @Override
    public FileMessageVO getFileMessageVO(FileMessage fileMessage, HttpServletRequest request) {
        FileMessageVO fileMessageVO = FileMessageVO.objToVo(fileMessage);
        // 1. 关联查询用户信息
        Long userId = fileMessage.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        fileMessageVO.setUser(userVO);
        return fileMessageVO;
    }

    /**
     * 将题目列表转换为题目视图列表，并关联查询用户信息。
     * @param fileMessagePage
     * @param request
     * @return
     */
    @Override
    public Page<FileMessageVO> getFileMessageVOPage(Page<FileMessage> fileMessagePage, HttpServletRequest request) {
        List<FileMessage> fileMessageList = fileMessagePage.getRecords();
        Page<FileMessageVO> fileMessageVOPage = new Page<>(fileMessagePage.getCurrent(), fileMessagePage.getSize(), fileMessagePage.getTotal());
        if (CollectionUtils.isEmpty(fileMessageList)) {
            return fileMessageVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = fileMessageList.stream().map(FileMessage::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<FileMessageVO> fileMessageVOList = fileMessageList.stream().map(fileMessage -> {
            FileMessageVO fileMessageVO = FileMessageVO.objToVo(fileMessage);
            Long userId = fileMessage.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            fileMessageVO.setUser(userService.getUserVO(user));
            return fileMessageVO;
        }).collect(Collectors.toList());
        fileMessageVOPage.setRecords(fileMessageVOList);
        return fileMessageVOPage;
    }

}




